package com.example.ylsys.plants.Utils;

import android.support.annotation.NonNull;
import android.text.TextUtils;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.List;
import java.util.Map;

public class BasicToolUtils {
    /**
     * 将时间戳转换为时间
     */
    public static String getTime(){
        SimpleDateFormat formatter   =   new  SimpleDateFormat  ("yyyy-MM-dd'T'HH:mm:ss'Z'");
        // 这里一定要设置GMT时区
        formatter.setTimeZone(new java.util.SimpleTimeZone(0, "GMT"));
        Date curDate =  new Date(System.currentTimeMillis());
        String timeStr= formatter.format(curDate);
        return timeStr;
    }

    /**
     *登陆时，使用的signature
     * @return Signature
     * @throws Exception
     */
    public static String GetSignature(String accessSecret, Map<String,String> paras) throws Exception{
        //去除签名关键字Key：
        if (paras.containsKey("Signature")) {
            paras.remove("Signature");
        }
        // 根据参数Key排序（顺序）
        java.util.TreeMap<String, String> sortParas = new java.util.TreeMap<String, String>();
        sortParas.putAll(paras);
        //构造待签名的请求串
        java.util.Iterator<String> it = sortParas.keySet().iterator();
        StringBuilder sortQueryStringTmp = new StringBuilder();
        while (it.hasNext()) {
            String key = it.next();
            sortQueryStringTmp.append("&").
                    append(specialUrlEncode(key)).
                    append("=").
                    append(specialUrlEncode(paras.get(key)));
        }
        // 去除第一个多余的&符号
        String sortedQueryString = sortQueryStringTmp.substring(1);
        String sign = sign(accessSecret, sortedQueryString);
        //String Signature = specialUrlEncode(sign);
        System.out.println(sortQueryStringTmp.toString());
        return sign;
    }

    public static String sign(String accessSecret, String stringToSign) throws Exception {
        javax.crypto.Mac mac = javax.crypto.Mac.getInstance("HmacSHA1");
        mac.init(new javax.crypto.spec.SecretKeySpec(accessSecret.getBytes("UTF-8"), "HmacSHA1"));
        byte[] signData = mac.doFinal(stringToSign.getBytes("UTF-8"));
        return new sun.misc.BASE64Encoder().encode(signData);
    }
    //特殊字符转换
    public static String specialUrlEncode(String value) throws Exception {
        return java.net.URLEncoder.encode(value, "UTF-8").replace("+", "%20").replace("*", "%2A").replace("%7E", "~");
    }

    /**
     * @param token
     * @param timestamp
     * @param nonce
     * @param sid
     * @return 登陆后请求数据
     */
    public static String CreateAuthSign(final String token, String timestamp, String nonce, String sid) {
        List<String> stringList = new ArrayList<String>();
        stringList.add(token);
        stringList.add(timestamp);
        stringList.add(nonce);
        stringList.add(sid);
        Collections.sort(stringList);
        String Signature = getSha1(TextUtils.join("", stringList));
        return Signature;
    }
    //sha1加密
    public static String getSha1(String str){
        if(str==null||str.length()==0){
            return null;
        }
        char hexDigits[] = {'0','1','2','3','4','5','6','7','8','9',
                'a','b','c','d','e','f'};
        try {
            MessageDigest mdTemp = MessageDigest.getInstance("SHA1");
            mdTemp.update(str.getBytes("UTF-8"));

            byte[] md = mdTemp.digest();
            int j = md.length;
            char buf[] = new char[j*2];
            int k = 0;
            for (int i = 0; i < j; i++) {
                byte byte0 = md[i];
                buf[k++] = hexDigits[byte0 >>> 4 & 0xf];
                buf[k++] = hexDigits[byte0 & 0xf];
            }
            return new String(buf);
        } catch (Exception e) {
            return null;
        }
    }
    //验证码md5加密
    @NonNull
    public static String md5(String string) {
        if (TextUtils.isEmpty(string)) {
            return "";
        }
        MessageDigest md5 = null;
        try {
            md5 = MessageDigest.getInstance("MD5");
            byte[] bytes = md5.digest(string.getBytes());
            StringBuilder result = new StringBuilder();
            for (byte b : bytes) {
                String temp = Integer.toHexString(b & 0xff);
                if (temp.length() == 1) {
                    temp = "0" + temp;
                }
                result.append(temp);
            }
            return result.toString().toUpperCase();
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        return "";
    }

}
